using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Abs.Core.Models;
using Abs.Core.Models.Blog;
using Abs.Core.Models.Booking;
using Abs.Core.Models.Room;
using Abs.Core.Models.User;

namespace Abs.Core.DAL.EntityFramework
{
    public class AbsContext : DbContext 
    {
        public  DbSet<User> Users { get; set; }

        internal DbSet<Room> Rooms { get; set; }
        internal DbSet<Day> Days { get; set; }
        internal DbSet<Role> Roles { get; set; }
        internal DbSet<RoomSchedule> RoomSchedules { get; set; }
        internal DbSet<Appointment> Appointments { get; set; }

        //Will be used for MVC 
        public DbSet<Status> Statuses { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }

        public AbsContext()
        {
            //Since some of the DbSet<Entity> access modifier are
            //set to internal, the EF cannot automatically instantiate.
            //Manually instantiate using Set<Entity>() method.
            //http://stackoverflow.com/questions/7636734/c-sharp-dbset-internal-object-cannot-be-got
            this.Users = this.Set<User>();
            this.Rooms = this.Set<Room>();
            this.Days = this.Set<Day>();
            this.Roles = this.Set<Role>();
            this.RoomSchedules = this.Set<RoomSchedule>();
            this.Appointments = this.Set<Appointment>();
        }//end of public AbsContext()

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            //Switch off the CascadeOnDelete to avoid the following error message:
            //
            //  "Introducing FOREIGN KEY constraint '...' on table '...' 
            //   may cause cycles or multiple cascade paths. 
            //   Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, 
            //   or modify other FOREIGN KEY constraints. 
            //   Could not create constraint. See previous errors." 
            //
            //http://msdn.microsoft.com/en-us/library/hh295843(v=VS.103).aspxx
            modelBuilder.Entity<Comment>()
                        .HasRequired(comment => comment.User)
                        .WithMany(user => user.Comments)
                        .HasForeignKey(comment => comment.UserEmail)
                        .WillCascadeOnDelete(false);
            Database.SetInitializer( new MigrateDatabaseToLatestVersion<AbsContext, Configuration>() );
        }//end of protected override void OnModelCreating(DbModelBuilder modelBuilder)
    }//end of public class AbsContext
}//end of namespace ABS.Models